<template>
    <div class="container">
		<el-form>
			<el-row>
				<el-col :span="4">
					<div style="width:200px;height:200px; border:1px solid #ccc;">
						<img  :src="api + ruleForm.jyImg" alt="" style="width:100%;height:100%;">
					</div>
				</el-col>
				<el-col :span="12" style="margin-left:30px;">
					<div>
						<span style="font-size:18px; font-weight:600;">{{ruleForm.jyName}}</span>
						<span class="mar-l">养殖批次号:{{ruleForm.batch}}</span>
					</div>
					<div style="margin-top:30px;font-size:14px;">
						<span>养殖规模：{{ruleForm.plantArea}}张</span>
						<span class="mar-l">养殖方式：{{ruleForm.way}}</span>
						<span class="mar-l">养殖时间：{{ruleForm.plantTime}}</span>
					</div>
					<div class="con">
						<div style="margin-top:10px;">
                            <span>养殖天数:{{this.iday}}天</span>
<!--                            <span style="position:absolute;left:200px;">前茬作物：{{ruleForm.prevPlant?ruleForm.prevPlant:'——'}}</span>-->
                        </div>
						<div style="margin-top:20px;">
                            <span>预计产出量：{{ruleForm.expOutPutsAcresNumber}}kg</span>
                            <span style="position:absolute;left:200px;">负责人：{{ruleForm.plantUserName}}</span>
                        </div>
					</div>
				</el-col>
			</el-row>
			<el-row style="margin-top:30px;background:#f5f5f5;">
				<el-tabs v-model="activeName" @tab-click="handleClick" >
					<el-tab-pane v-for="(item,index) in list" :key="index" :label="'第' + (index+1)+ '年'" :name="'第' + (index+1) + '年'" >
						<div style="display: flex; flex-wrap: wrap;justify-content: flex-start;">
							 <div class="addtend" v-for="(s,index) in item" :key="index"  style="margin:30px;font-size:8px;position:relative;">
								<div style="width:20px; margin:0 auto;line-height:24px;font-size:12px;position: absolute;right:0px;top:0px;background:#31ad5d;text-align: center;color:white;">{{s.type}}</div>
								<div style='padding: 10px'>
                                    <el-form-item label="操作时间">
                                        {{s.beginTime}}至{{s.endTime}}
                                    </el-form-item>
                                    <el-form-item label="操作人">
                                        {{s.principalName}}
                                        <!--									<el-button type="success" round size="mini" v-if="s.finished == true" style="float: right;margin-right:20px;">任务完成</el-button>-->
                                        <!--									<el-button type="danger" round size="mini" v-if="s.finished == false" @click="gotask(s)" style="float: right;margin-right:20px;">任务未完成</el-button>-->
                                    </el-form-item>
                                </div>
								<div class='poster'>
                                    <img v-if="s.img != '' && s.img != null" :src="$store.state.plantImg + s.img" alt="" style="width:280px;height:130px; padding: 10px;border-bottom: 1px solid #e4e4e4">
                                    <img class='statusCheck' :src='s.auditState == 1?check:checked'/>
                                </div>
                                    <div class='menu-box'>
                                        <span v-if='s.auditState == 1' class='edit' @click='edit(s)'><i class='el-icon-edit'></i>修改</span>
                                        <span v-if='s.auditState == 1' class='del' @click='del(s)'><i class='el-icon-delete'></i>删除</span>
                                        <span v-if='s.auditState == 1' class='confirm' @click='confirm(s)'><i class='el-icon-check'></i>确认审核</span>
                                        <span v-if='s.auditState != 1' class='confirm' @click='unlock(s)'><i class='el-icon-lock'></i>锁定解除</span>
                                    </div>
							</div>
						</div>
					</el-tab-pane>
				</el-tabs>
				<!-- <div style="display: flex;flex-direction: row;justify-content: flex-start;flex-wrap: wrap;" v-else>
					<div class="addtend" v-for="(s,index) in onelist" :key="index"  style="margin:30px;padding:10px;font-size:8px;position:relative;">
						<div style="width:20px; margin:0 auto;line-height:24px;font-size:12px;position: absolute;right:0px;top:0px;background:#3aa0ff;text-align: center;color:white;">{{s.type}}</div>
						<el-form-item label="操作时间">
							{{s.beginTime}}至{{s.endTime}}
						</el-form-item>
						<el-form-item label="操作人">
							{{s.principalName}}
							<el-button type="success" round size="mini" v-if="s.principalName !='' && s.principalName != null" style="float: right;margin-right:20px;">任务完成</el-button>
							<el-button type="danger" round size="mini" v-if="s.principalName == null" style="float: right;margin-right:20px;">任务未完成</el-button>
						</el-form-item>
						<img :src="$store.state.imageUrls + s.img" alt="" style="width:300px;height:130px;">
					</div>
				</div> -->
			</el-row>
			<el-form-item class="footerFixed" label-width="0px">
			    <div class='fixed'>
                    <el-button @click="backPage" >返回</el-button>
                </div>
			</el-form-item>
		</el-form>
        <el-dialog :visible.sync="dialogVisible">
            <el-form :model="formData" ref='formData' :rules="rules" label-position="right" label-width="120px">
                <el-row :gutter='60'>
                    <el-col :span="10">
                        <el-form-item label='方式：' prop="way">
                            <el-select v-model="formData.way" placeholder="请选择" style="width: 300px">
                                <el-option label="机械" value="机械"></el-option>
                                <el-option label="人工" value="人工"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="开始时间：" prop="beginTime">
                            <el-date-picker
                                v-model="formData.beginTime"
                                type="date"
                                @change="vaildDate"
                                value-format="yyyy-MM-dd"
                                placeholder
                                style="width: 300px"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="操作图片：">
                            <el-upload
                                class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreview"
                                :auto-upload="false"
                            >
                                <img v-if="headImg" :src="headImg" class="avatar" />
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            jpg、png、gif格式，不超过20MB
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人：" prop="principalName">
                            <el-select
                                v-model="formData.principalName"
                                style="width: 300px"
                                value-key="id"
                                placeholder=""
                            >
                                <el-option v-for="item in userAll" :key="item.id" :label="item.name" :value="item">{{item.name }}</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="结束时间：" prop="endTime">
                            <el-date-picker
                                v-model="formData.endTime"
                                type="date"
                                @change="vaildDate"
                                value-format="yyyy-MM-dd"
                                style="width: 300px"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="执行标准：">
                            <el-upload
                                class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreviewExcute"
                                :auto-upload="false"
                            >
                                <img v-if="excuteImg" :src="excuteImg" class="avatar" />
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            jpg、png、gif格式，不超过20MB
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row style="margin-top:10px;">
                    <h3 style='margin: 20px 0'>用工记录</h3>
                    <el-col>
                        <h4 v-if='hasFile'>{{formData.file.name}}</h4>
                    </el-col>
                    <el-row>
                        <el-col style='padding: 10px 0'>
                            <el-button class='theme-button' @click='download' style='float: right'>导出</el-button>
                            <el-upload
                                class="upload-import"
                                style='float: left;background-color: initial'
                                ref="upload"
                                action=""
                                :on-change="importExcel"
                                accept=".xlsx,.xls"
                                :show-file-list='false'
                                :auto-upload="false">
                                <el-button class='theme-button' slot="trigger" size="small">导入模板</el-button>
                            </el-upload>
                            <el-button class='theme-button' @click='downloadTemplate'>下载导入模板</el-button>
                        </el-col>
                    </el-row>
                </el-row>
                </el-form>
                <el-table border stripe :data="workerTableData">
                <el-table-column align='center' prop="name" label="姓名">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.name" placeholder="请输入内容" @blur='saveWorkTable(scope.row)'></el-input>
                    </template>
                </el-table-column>
                <el-table-column align='center' prop="tache" label="用工类型"></el-table-column>
                <el-table-column align='center' prop="startDate" label="开始时间"></el-table-column>
                <el-table-column align='center' prop="endDate" label="结束时间"></el-table-column>
                <el-table-column align='center' prop="workHours" label="工时">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.workHours" placeholder="请输入内容" @blur='saveWorkTable(scope.row)'></el-input>
                    </template>
                </el-table-column>
                <el-table-column align='center' prop="money" label="用工金额(元)">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.money" placeholder="请输入内容" @blur='saveWorkTable(scope.row)'>
                            <template slot="suffix">
                                <span style='position: absolute;top: 4px;right: 5px'>元</span>
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column align='center'  label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
                <el-pagination background :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>

            <div slot='footer'>
                <el-button @click="cancel">取消</el-button>
                <el-button class='theme-button'  @click="diaLogConfirm">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    plant_findById,
    farm_findByUserId,
    plant_view,
    auditPlantOperation,
    deletePlantOperation,
    user_findByAll,
    updatePlantLabor,
    getPlantLaborList,
    updatePlantOperation,
    farm_finish,
    farm_save
} from '@/request/api';
import axios from 'axios';
    export default {
        data(){
            return{
                check:require('@/assets/img/check.png'),
                checked:require('@/assets/img/checked.png'),
                iday:'',
                api:this.$store.state.plantImg,
                id:'',
                activeName:'第1年',
                ruleForm:'',
				list:[],
				i:'',
				onelist:[],
                dialogVisible:false,
                rules: {
                    way: [{ required: true, message: '不能为空', trigger: 'change' }],
                    beginTime: [{ required: true, message: '不能为空', trigger: 'change' }],
                    principalName: [{ required: true, message: '不能为空', trigger: 'change' }],
                    endTime: [{ required: true, message: '不能为空', trigger: 'change' }],
                    soilName: [{ required: true, message: '不能为空', trigger: 'change' }],
                    type:[{required: true, message: '不能为空', trigger: 'change'}],
                },
                headImg:'',
                excuteImg:'',
                hasFile:false,
                userAll:[],
                currentPage:1,
                pageSize:10,
                total:0,
                workerTableData:[],

                formData:{

                },
            }
        },
        watch:{
            'formData.file'(val){
                if(val){
                    this.hasFile = true
                }else{
                    this.hasFile = false
                }
            }
        },
        mounted(){
            this.id = this.$route.query.id
            this.init()
            this.getHeadManList()

        },
        methods:{
            //查询用工记录数据
            async getWorkDetail(){
                let params = {
                    page: this.currentPage,
                    PageSize: this.pageSize,
                    batch:this.ruleForm.batch,
                    tache:this.formData.type,
                    type:'农事',
                }
                const res = await getPlantLaborList(params)
                if(res.code == 200){
                    this.workerTableData = res.data.content
                    this.total = res.data.totalElements
                }
            },
            handleSizeChange(v){
                this.pageSize = v
                this.getWorkDetail()
            },
            handleCurrentChange(val) {
                this.pageSize = val
                this.getWorkDetail()
            },
            //下载xlsx文件
            downloadFile(url,fileName){
                //由于之前的前端没有封装导入模板接口，所以只能用axios
                axios.get(localStorage.getItem('requestUrl')+url,{responseType:'arraybuffer'}).then(res=>{
                    const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
                    const url = window.URL.createObjectURL(blob)
                    const link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download',`${fileName}.xlsx`)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    window.URL.revokeObjectURL(url)
                    this.$notify({
                        title: '操作成功',
                        message: '下载成功',
                        type: 'success'
                    })
                })
            },
            // 导出
            async download() {
                this.downloadFile(`/labor/exportLaborData?batch=${this.ruleForm.batch}`,'用工记录')
            },
            //用工删除
            async handleDel(params){
                const res = await deletePlantLabor('?id='+params.id)
                if(res.code == 200){
                    this.$notify({
                        title: '操作成功',
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getWorkDetail()
                }
            },
            //用工保存
            async saveWorkTable(params){
                const res = await updatePlantLabor(params)
                if(res.code == 200){
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    })
                }
            },
             diaLogConfirm(){
                this.$refs.formData.validate(async(valid)=>{
                    if(valid){
                        let formData = new FormData();
                        for (var a in this.formData) {
                            if (this.formData[a] == null || this.formData[a] == 'null') {
                                this.formData[a] = '';
                                formData.append(a, '');
                            } else {
                                formData.append(a, this.formData[a]);
                            }
                        }
                        const res = await updatePlantOperation(formData)
                        console.log(res);
                        if(res.code == 200){
                            this.$notify({
                                title: '操作成功',
                                message: '保存成功',
                                type: 'success'
                            })
                            this.dialogVisible = false
                        }
                    }
                })
            },
            cancel(){
                this.formData = {

                }
                this.$refs['formData'].resetFields()
                this.dialogVisible = false
            },
            async edit(item){
                console.log(item);
                this.dialogVisible = true
                this.formData = item
                this.headImg = this.$store.state.imageUrls+item.img
                this.excuteImg = this.$store.state.imageUrls+item.standardImg
                this.getWorkDetail()
            },
            getHeadManList(){
                user_findByAll('').then((res) => {
                    this.userAll = res.data;
                });
            },
            importExcel(file){
                this.formData.file = file.raw
                this.$notify({
                    title: '操作成功',
                    message: '导入成功',
                    type: 'success'
                })
                this.hasFile = true
            },
            //下载导入模板
            async downloadTemplate() {
                //type (1=农事用工, 2=养殖用工, 3=加工用工, 4=采收用工)
                this.downloadFile('labor/exportLaborTemplate?type=1','农事导入模板')
            },
            imgPreviewExcute(file, fileList) {
                this.excuteImg = URL.createObjectURL(file.raw);
                let fileName = file.name;
                let regex = /(.jpg|.gif|.png|.jpeg)$/;
                if (regex.test(fileName.toLowerCase())) {
                    this.formData.standardImgFile = file.raw;
                    this.formData.standardImg = file.name;
                } else {
                    this.$message.error('请选择图片文件');
                }
            },
            imgPreview(file, fileList) {
                this.headImg = URL.createObjectURL(file.raw);
                let fileName = file.name;
                let regex = /(.jpg|.gif|.png|.jpeg)$/;
                if (regex.test(fileName.toLowerCase())) {
                    this.formData.files = file.raw;
                    this.formData.img = file.name;
                } else {
                    this.$message.error('请选择图片文件');
                }
            },
            vaildDate() {
                if (this.formData.beginTime != '' && this.formData.endTime != '') {
                    var oDate1 = new Date(this.formData.beginTime);
                    var oDate2 = new Date(this.formData.endTime);
                    if (oDate1 > oDate2) {
                        this.$notify({
                            title: '提示',
                            message: '开始时间不得早于结束时间',
                            type: 'info'
                        });
                        this.formData.beginTime = '';
                        this.formData.endTime = '';
                    }
                }
            },
            async del(item){
                let id = item.id
                const res = await deletePlantOperation([id])
                if (res){
                    this.$notify({
                        title: '提示',
                        message: '删除成功',
                        type: 'success'
                    });
                    this.init()
                }
            },
            async confirm(item){
                const res = await auditPlantOperation('?id='+item.id+'&auditState=2')
                if (res.code == 200){
                    this.$notify({
                        title: '提示',
                        message: '审核成功',
                        type: 'success'
                    });
                    this.init()
                }
            },
            async unlock(item){
                const res = await auditPlantOperation('?id='+item.id+'&auditState=1')
                if (res.code == 200){
                    this.$notify({
                        title: '提示',
                        message: '解锁成功',
                        type: 'success'
                    });
                    this.init()
                }
            },
			gotask(s){
				if(s.status == 2){
					this.$router.push({
						path:'/plant/tending/addtending',
						query:{
							sid:s.id
						}
					})
				}else{
					this.$notify({
						title: '提示',
						message: '您不是该任务执行人',
						type: 'info'
					});
				}

			},
			backPage(){
				this.$router.go(-1)
			},
            init(){
                //看不懂之前的人写的这段什么意思，声明这么多相同全局变量
				plant_view(this.id).then((res)=>{
					this.ruleForm = res.plant
					var date1 =  new Date().getFullYear() +  "-" +(new Date().getMonth() + 1).toString().padStart(2, "0") +  "-" + new Date().getDate().toString().padStart(2, "0")
				   var date2 = this.ruleForm.plantTime.replace(/\//g,"-")
				   var date1 = Date.parse(date1)
				   var date2 = Date.parse(date2)

				   var day =  date1 - date2
				   var day = Math.abs(day)
				   this.iday = Math.floor(day/(24*3600*1000))
				   this.list = res.farms
				})

            },
            handleClick(){

            },
            goadded(){
                this.$router.push({
                    path:'/plant/tending/addtending',
					query:{id:this.id}
                })
            }
        }
    }
</script>

<style lang='less' scoped>
@import "@/assets/css/common.less";
.el-pagination{
    margin-top: 10px;
    text-align: right;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.poster{
    width: 100%;
    height: 153px;
    position: relative;
    .statusCheck{
        position: absolute;
        width: 80px;
        right:0;
        top: 0;
    }
}
.menu-box{
    user-select: none;
    font-size: 14px;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    cursor: pointer;
    .edit{
        width: 70px;
        color:#1BC46D;
        border-right: 1px solid #e4e4e4;
    }
    .del{
        width: 70px;
        color: #f63109;
        border-right: 1px solid #e4e4e4;

    }
    .confirm{
        color: #00aef6;
    }
}
/deep/.el-tabs__item.is-active {
    color: #1BC46D;
}

/deep/.el-tabs__active-bar {
    background-color: #1BC46D;
}
    .mar-l{
        margin-left:30px;
    }
    .con{
        width:400px;
        /* height:100px; */
        background:#F6F7FA;
        border-radius:10px;
        margin-top:25px;
        padding:15px;
        font-size:14px;
        position:relative;
    }
    .addtend{
        display:inline-block;
        width: 300px;
        margin-left:20px;

        /* margin:20px; */
        //height:200px;
        /* line-height:200px;
        text-align: center; */
        background:#fff;
    }
    //.el-form-item{
	//	margin-bottom:0px;
	//}
</style>
